import { _decorator, Component, Node, Widget, Vec2, UITransform, Touch, v2, v3, Layers } from 'cc';
import ResourceManager from '../runTime/resourceManager';
import { TILE_TYPE_ENUM } from '../enums';
import { createUINode } from '../../utils';
import { TileManager } from '../../base/tileManager';
const { ccclass, property } = _decorator;

@ccclass('JoyStickManager')
export class JoyStickManager extends Component {
    private _stick: Node;
    private _max_r = 100;
    private _min_r = 20;

    public _dir: Vec2 = v2(0, 0); // 单位向量


    async init() {
        this._stick = createUINode("stick");
        this._stick.layer = 1 << Layers.nameToLayer("DEFAULT");
        const tileManager = this._stick.addComponent(TileManager);
        const spriteFrame = await ResourceManager.Instance.load("stick/stick/spriteFrame")
        tileManager.init(TILE_TYPE_ENUM.BACK_GROUND, spriteFrame)
        tileManager.uiTransformChange(100, 100);
        this._stick.setParent(this.node)

        // const graphics = this._stick.addComponent(Graphics);
        // graphics.lineWidth = 2; // 线宽
        // graphics.strokeColor = Color.WHITE; // 线条颜色
        // graphics.fillColor = Color.WHITE; // 填充颜色（半透明）
        // graphics.circle(50, 50, 50); // 圆心x, 圆心y, 半径
        // graphics.fill(); // 填充圆形（如果你想要填充效果）
        // graphics.stroke(); // 绘制线条（如果你想要线条效果）

        const widget = this._stick.parent.addComponent(Widget);
        widget.isAlignBottom = true;
        widget.isAlignLeft = true;
        widget.bottom = -400;
        widget.left = 0;

        // 圆点触摸事件
        this.stickEvent();

    }

    private stickEvent(): void {
        this._stick.on(Node.EventType.TOUCH_MOVE, this.onStickMove, this);
        this._stick.on(Node.EventType.TOUCH_END, () => this.onStickEnd());
        this._stick.on(Node.EventType.TOUCH_CANCEL, () => this.onStickEnd());
    }

    onStickMove(e: Touch): void {
        const screen_pos: Vec2 = e.getLocation();
        const pos = this._stick.parent.getComponent(UITransform).convertToNodeSpaceAR(v3(screen_pos.x * 2 + 25, screen_pos.y * 2 + 25, 0));
        const len: number = pos.length();

        if (len <= this._min_r) {
            this._stick.setPosition(pos);
            return;
        }

        this._dir.x = pos.x / len; // cos
        this._dir.y =  pos.y / len; // sin

        if (len > this._max_r) {
            pos.x = pos.x * this._max_r / len;
            pos.y = pos.y * this._max_r / len;
        }

        this._stick.setPosition(pos);
    }

    onStickEnd(): void {
        this._dir = v2(0, 0);
        this._stick.setPosition(0, 0);
    }
}
